
from flask import render_template, current_app, session, jsonify, request, g

from application import constants
from application.models import User, News, Category
from application.utils.common import user_login_data
from application.utils.response_code import RET
from . import index_blue

@index_blue.route("/news_list")
def news_list():
    """
    获取首页新闻数据
        1.获取参数
        2.校验参数
    :return: 
    """
    # 1.获取参数
    cid = request.args.get("cid", "1")
    page = request.args.get("page", "1")
    per_page = request.args.get("per_page", "10")

    # 2.校验参数
    try:
        cid = int(cid)
        page = int(page)
        per_page = int(per_page)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数有误")

    filters = [News.status == 0]
    if cid != 1:  # 查询的不是最新的数据
        # 需要添加条件
        filters.append(News.category_id == cid)

    # 3.查询数据
    try:
        paginate = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page, per_page, False)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据查询错误")

    # 取到当前页的数据
    new_model_list = paginate.items  # 模型对象列表
    total_page = paginate.pages  # 总页数
    current_page = paginate.page  # 当前页

    # 将模型对象列表转成字典列表
    news_dict_li = []
    for news in new_model_list:
        news_dict_li.append(news.to_basic_dict())

    data = {
        "total_page" : total_page,
        "current_page" :current_page,
        "news_dict_li" :news_dict_li
    }
    return jsonify(errno=RET.OK, errmsg="OK", data=data)


@index_blue.route("/")
@user_login_data
def index():
    """
    显示首页
    1.如果用户已经登录,将当前登录用户的数据传到模板中,供模板显示

    """
    # 显示用户登录逻辑
    user = g.user

    # 右侧的新闻排行的逻辑
    news_list = []
    try:
        news_list = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    except Exception as e:
        current_app.logger.error(e)

    news_dict_li = []

    # 遍历对象列表,将对象的字典添加到字典列表中
    for news in news_list:
        news_dict_li.append(news.to_basic_dict())


    # 查询分类逻辑,通过模板的形式渲染出来
    categories = Category.query.all()

    category_li = []
    for category in categories:
        category_li.append(category.to_dict())

    data = {
        # 三元表达式 如果用户有值，那么返回user.to_dict() 否则返回None
        "user" : user.to_dict() if user else None,
        "news_dict_li": news_dict_li,
        "category_li" : category_li
    }

    return render_template('news/index.html', data =data)


# 打开网页时,浏览器会默认请求路径+favicon.ico作网站标签的小图标
@index_blue.route("/favicon.ico")
def favicon():

    # send_static_file 是flask 去查找指定的静态文件所调用的方法
    return  current_app.send_static_file("news/favicon.ico")



